'''
Date: 2023-12-01 12:19:01
Author: WT-W-PC
LastEditors: WT-W-PC
LastEditTime: 2023-12-05 13:16:10
Description: 
装饰器assistant支持在函数进入和退出前输出日志
JsonConfig支持对配置文件进行读写
自定义异常类CommonException支持自定义异常
还支持获取格式化后的本地时间以及暂定等功能函数
'''


import logging
import time
import random
import json
import os

logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)

# 打印函数的出入口,@assistant相当于先初始化,初始化函数也会调用__call__,然后再调用assistant(func)
# 装饰器不带括号，原函数直接作为参数传给装饰器，类似desc(func)
# 装饰器带括号，相当于装饰器的方法dec先执行，dec()运行后返回一个内层的函数inner_desc， 由这个inner_desc作为装饰器，原函数实际是传给inner_desc，等价于inner_desc(f)
# 装饰器类
class assistant():
    # 装饰器使用时必须要带括号，因为这个要先执行这个函数
    def __init__(self, level='INFO'):
        self.level = level
        
    # 被装饰的函数执行时，先进入装饰器
    def __call__(self, func):
        def wrapper(*args, **kwargs):
            log_msg = f'function[{func.__qualname__}] begins............'
            self.__log(log_msg)
            
            res = func(*args, **kwargs)
            
            log_msg = f'function[{func.__qualname__}] ends............\n'
            self.__log(log_msg)
            return res
        return wrapper

    def __log(self, msg):
        if self.level == 'DEBUG':
            logging.debug(msg)
        elif self.level == 'ERROR':
            logging.error(msg)
        else:
            logging.info(msg)
            
# 加载json格式的配置文件
class JsonConfig():
    def __init__(self, file_dir):
        self.config_file_dir = file_dir
        self.data = {}
        self._status = False
    
    @property
    def status(self):
        return self._status
    
    # 初始化配置文件
    def init(self):
        if os.path.exists(self.config_file_dir):
            try:
                with open(self.config_file_dir, 'r') as f:
                    self.data = json.load(f)
                    self._status = True
            except Exception as e:
                self._status = False
                logging.error(e)
        else:
            log_msg = f'{self.config_file_dir} does not exist.'
            logging.error(log_msg)
            self._status = False
        
        return self._status
                   
    # 读取json配置文件
    def read(self, key):
        return self.data.get(key)
        
        
    # 写入json配置文件
    def write(self, newdict):
        result = False
        if self._status:
            try:
                self.data.update(newdict)
                with open(self.config_file_dir, 'w') as f:
                    # 格式化更新文件
                    json.dump(self.data, f, indent=4)
                result = True
            except Exception as e:
                logging.error(e)
        return result
    
# 自定义异常
class CommonException(Exception):
    def __init__(self, msg):
        self.__msg = msg
        super().__init__(self.__msg)
        
    def __str__(self):
        return str(self.__msg)
    

# 获取本地时间，格式为YYYY-mm-DD HH:MM:SS
def getlocaltime():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

def gettodaydate():
    today_date = int(time.strftime("%d", time.localtime()))
    return str(today_date)

# 随机暂停一段时间，单位为秒
def pause(start=1, end=3):
    tick = random.uniform(start, end)
    time.sleep(tick)
    return tick
    